package com.whutosa.template.server.interceptor;

import com.whutosa.template.server.model.User;
import com.whutosa.template.server.service.UserService;
import com.whutosa.template.server.utils.JedisUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * Created by 19110 on 2016/9/28.
 */
@Component
public class ChatWebSocketInterceptor implements HandshakeInterceptor {
    private static final Logger log = LogManager.getRootLogger();
    @Autowired
    private UserService userService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) request;
            String token = httpRequest.getServletRequest().getParameter("token");
            log.info("token = \t" + token);
            String uid = JedisUtil.get(token);
            if (uid == null) {
                return false;
            } else {
                User user = userService.getUser(uid);
                attributes.put("user", user);
                return true;
            }
        } else {
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
